

import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:custom_social_share/custom_social_share.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/model/product_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/core/view/date_picker.dart';
import 'package:smart_freezer/core/view/update_location.dart';
import 'package:smart_freezer/core/view/update_time.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';
import 'package:ty_smart_home/ty_smart_home.dart';

import '../../../../core/utils/color_util.dart';
import 'device_share_list.dart';

class DeviceShare extends StatefulWidget {
  const DeviceShare({Key? key}) : super(key: key);

  @override
  State<DeviceShare> createState() => _DeviceShareState();
}

class _DeviceShareState extends State<DeviceShare> {

  List _dataList = [
    {"title": LocaleKeys.device_info_share_wechat.trc(), "content": "", "icon": IconNames.share_weixin},
    {"title": LocaleKeys.device_info_share_whatsapp.trc(), "content": "", "icon": IconNames.share_whatsapp},
    {"title": LocaleKeys.device_info_share_line.trc(), "content": "", "icon": IconNames.share_line},
    // {"title": "", "content": "", "icon": ""},
    // {"title": LocaleKeys.device_info_share_people.trc(), "content": "", "icon": IconNames.share_ble},
  ];

  List<Map<String, String>> _floorList = [];

  ProductModel _productModel = Get.arguments as ProductModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // _getDeviceInfo();

    _dataList = [
      {"title": LocaleKeys.device_info_share_wechat.trc(), "content": "", "icon": IconNames.share_weixin},
      {"title": LocaleKeys.device_info_share_whatsapp.trc(), "content": "", "icon": IconNames.share_whatsapp},
      {"title": LocaleKeys.device_info_share_line.trc(), "content": "", "icon": IconNames.share_line},
      {"title": LocaleKeys.device_info_share_email.trc(), "content": "", "icon": IconNames.share_email},
      // {"title": "", "content": "", "icon": ""},
      // {"title": LocaleKeys.device_info_share_people.trc(), "content": "${_productModel.shareCount}人", "icon": IconNames.share_ble},
    ];

  }

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 1,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(LocaleKeys.device_info_device_share.trc(),),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
        color: isDarkMode ? Colors.black : MainCommon.bgGreyColor,
        child: ListView.builder(
            itemCount: _dataList.length,
            itemBuilder: (context, index){
              final title = _dataList[index]["title"] as String;
              final content = _dataList[index]["content"];
              final icon = _dataList[index]["icon"];

              return title.isNotEmpty ? InkWell(
                onTap: () async {
                  if(title == LocaleKeys.device_info_share_people.trc()) {
                    Get.toNamed(LCRouter.device_share_list);
                  }else{
                    _startShare(2, index);

                    return;
                    // 不弹出编辑框
                    showModalBottomSheet(
                        context: context,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                        ),
                        builder: (_) {
                          return PermissionWidget(permission: 0, confirmTap: (selectValue) {
                            // _editShareList(id, selectValue.toString());

                            // 开始分享
                            _startShare(selectValue, index);
                          },);
                        }
                    );
                  }
                },
                child: Container(
                  color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                  height: 50,
                  padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Column(
                    children: [
                      Container(
                        height: 49,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Image.asset(icon, width: 30,),
                                SizedBox(width: 10,),
                                Text(title, style: TextStyle(fontSize: 16),),
                              ],
                            ),

                            Row(
                              children: [
                                Text(content, style: TextStyle(fontSize: 15, color: Colors.grey),),
                                Icon(Icons.chevron_right, color: Colors.grey.shade400,),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Divider(
                        height: 1,
                        indent: 5,
                        endIndent: 5,
                      ),
                    ],
                  ),
                ),
              ) : SizedBox(height: 10,);
        }),
      ),
    );
  }

  /// 保存分享
  _startShare(int permission, int index) async {

    // List<ShareWith> list = await CustomSocialShare().getInstalledAppsForShare();
    // logs(list);
    //
    // CustomSocialShare().to(ShareWith.wechat, "邀请您一起使用Williams通用年控制器(WUMC3)。");

    // final result = await TySmartHome.inviteShare(_productModel.devId, LocalStorage.getCountryCode(), LocalStorage.getUID());
    // logs("分享结果: $result");
    // if(result == 0) { // 需要重新登录
    //   Get.offNamed(LCRouter.login);
    // }
    // return;

    // _showBackLoginDialog();return;

    final params = {"productId": _productModel.id, "permission": "$permission"};
    ResultData data = await AppApi.getInstance().saveShareInfo(params);
    if(data.code == 0){
      // 开始涂鸦分享
      var platformList = [ShareWith.wechat, ShareWith.whatsapp, ShareWith.line, ShareWith.email, ];
      if(index <= 3) {
        // if(Platform.isIOS){
        //   final shareURL = "http://williams.benwuyou.cn/admin/share?tuyaShareId=${0}&williamShareId=${data.data}";
        //   CustomSocialShare().to(platformList[index], "邀请您一起使用Williams通用年控制器. $shareURL");
        //   return;
        // }

        final result = await TySmartHome.inviteShare(_productModel.devId, LocalStorage.getCountryCode(), LocalStorage.getTyUID());

        final shareId = int.tryParse(result["result"]) ?? 0;
        final errorCode = result["code"].toString();

        final shareURL = "http://www.williams-conetchill.com/admin/share?tuyaShareId=${shareId}&williamShareId=${data.data}";
        final shareTip = "${LocalStorage.getAccount()}${LocaleKeys.wifi_share_tip.trc()} $shareURL";

        if(shareId > 0) {  // 分享ID
          CustomSocialShare().to(platformList[index], shareTip);
        }else{
          // 全局错误码 https://developer.tuya.com/cn/docs/iot/error-code?id=K989ruxx88swc
          if(errorCode.startsWith("10") || errorCode.startsWith("11")){  // iOS 端无法获取到 error code, 此方法只能用在 Android 端
            _showBackLoginDialog();
            return;
          }else if(errorCode.startsWith("20") || errorCode.startsWith("21")){
            _showWiFIConfigDialog();
          }

        }
      }

    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  _showBackLoginDialog() {
    showOkCancelAlertDialog(
      context: context,
      message: LocaleKeys.other_session_tip.trc(),
      barrierDismissible: false,
      useActionSheetForIOS: true,
      onWillPop: () async { return false;},
      builder: (context, child) => Theme(
        data: ThemeData(
            primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
            dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
            colorScheme: ColorScheme(
              primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
              primaryVariant: Colors.white,
              secondary: Colors.green,
              background: Colors.white,
              error: Colors.red,
              brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
              onBackground: Colors.pink,
              secondaryVariant: Colors.white,
              onError: Colors.yellow,
              onPrimary: Colors.red, //顶部栏字体颜色
              onSecondary: Colors.black,
              onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
              surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
            )),
        child: child,
      ),
    ).then((value) {
      if(value == OkCancelResult.ok){
        Get.offNamed(LCRouter.login);
      }
    });

  }

  _showWiFIConfigDialog() {
    showOkCancelAlertDialog(
      context: context,
      message: LocaleKeys.other_wifi_tip.trc(),
      cancelLabel: LocaleKeys.login_cancel.trc(),
      okLabel: LocaleKeys.other_wifi_config.trc(),
      builder: (context, child) => Theme(
        data: ThemeData(
            primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
            dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
            colorScheme: ColorScheme(
              primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
              primaryVariant: Colors.white,
              secondary: Colors.green,
              background: Colors.white,
              error: Colors.red,
              brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
              onBackground: Colors.pink,
              secondaryVariant: Colors.white,
              onError: Colors.yellow,
              onPrimary: Colors.red, //顶部栏字体颜色
              onSecondary: Colors.black,
              onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
              surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
            )),
        child: child,
      ),
    ).then((value) {
      if(value == OkCancelResult.ok){
        Get.offNamed(LCRouter.wifi_page);
      }
    });
  }

}
